package com.xingchi.tornado.storage.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.xingchi.tornado.core.context.SpringContextHolder;
import com.xingchi.tornado.storage.core.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 枚举值序列化处理
 *
 * @author xiaoya
 * @date 2023/6/16 15:33
 * @modified xiaoya
 */
@Slf4j
public class JsonFileUrlSerializer extends JsonSerializer<Long> implements ContextualSerializer {

    private String fieldName;
    private String suffix;
    private FileUploadService fileUploadService;

    public JsonFileUrlSerializer() {
    }

    public JsonFileUrlSerializer(String suffix, String fieldName) {
        this.fieldName = fieldName;
        this.suffix = suffix;
        this.fileUploadService = SpringContextHolder.getBean(FileUploadService.class);
    }

    @Override
    public void serialize(Long source, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (source != null) {
            // 则查询对应的文件信息
            jsonGenerator.writeNumber(source);
            if (StringUtils.isNotBlank(suffix)) {
                try {
                    jsonGenerator.writeStringField(fieldName + "Url", fileUploadService.getUrl(source));
                } catch (IOException e) {
                    log.warn("文件不存在");
                }
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            if (Objects.equals(beanProperty.getType().getRawClass(), Long.class)) {
                JsonFileUrl jsonFileUrl = beanProperty.getAnnotation(JsonFileUrl.class);
                if (jsonFileUrl == null) {
                    jsonFileUrl = beanProperty.getContextAnnotation(JsonFileUrl.class);
                }
                if (jsonFileUrl != null) {
                    return new JsonFileUrlSerializer(jsonFileUrl.value(), beanProperty.getName());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}
